<template>

	<view class="">
		<view class="authentication">
			<view class="title weight">基本信息</view>
			<view class="module">
				<view class="upLoad">
					<van-uploader name="cureList" :max-count="1" :file-list="upLoad.cureList" :after-read="afterRead"
						@delete="deleteFile">
						<van-button>
							<van-icon name="plus" style="color:#47A49B;" />
						</van-button>
					</van-uploader>
					<text>上传头像</text>
				</view>
				<van-cell-group>
					<van-field v-model="dataValue.name" label="姓名" clearable required placeholder="请输入姓名"
						@input="setInputValue('name', $event)" />
					<van-field v-model="dataValue.phone" label="手机号码" clearable required type='number'
						placeholder="请输入手机号码" maxlength="11" @input="setInputValue('phone', $event)" />
					<van-field label="性别" clearable required readonly placeholder="请选择性别" :value="dataValue.sex"
						@click.native="showPop('sexList', 'name')" />
					<van-field v-model="dataValue.cardNo" label="身份证号码" clearable required type='cardNo'
						placeholder="请输入身份证号码" @input="setInputValue('cardNo', $event)" />
						<van-field v-if="birthday" v-model="dataValue.birthDate" label="出生日期" clearable required readonly
							placeholder="请输入出生日期" />
					<van-field label="籍贯" clearable required readonly placeholder="请选择籍贯" :value="dataValue.nativePlace"
						@click.native="showPop('areaList', 'areaList', 'area')" />
<!-- 						<van-field label="文化程度" clearable required readonly placeholder="请选择文化程度" :value="dataValue.education"
							@click.native="showPop('educationList', 'name')" /> -->
					<!-- <van-field v-model="dataValue.wechat" label="微信号码" clearable required placeholder="请输入微信号码"
						@input="setInputValue('wechat', $event)" /> -->
					<!-- <van-field v-model="dataValue.specialty" label="特长" clearable required placeholder="请输入特长"
						@input="setInputValue('specialty', $event)" />
<van-field title-width="240rpx" :value="dataValue.addPeriodIdsName" label="可提供服务的时间" clearable required
						readonly placeholder="请选择可提供服务的时间" @click.native="setCheckValue('addPeriodIds', 'weekList')" />
					<van-field title-width="240rpx" :value="dataValue.addPurposeIdsName" label="志愿者服务方向" clearable required
						readonly placeholder="请选择志愿者服务方向"
						@click.native="setCheckValue('addPurposeIds', 'orientationList')" />
					<van-field v-model="dataValue.resume" label="个人简历" type="textarea" placeholder="请详细描述,以便了解情况" :autosize="{ minHeight: 40 }"
						@input="setInputValue('resume', $event)" /> -->
				</van-cell-group>

				<van-cell-group>
					<!-- <van-field v-model="dataValue.nation" label="民族" clearable placeholder="请输入民族" @input="setInputValue('nation', $event)" />
					<van-field v-model="dataValue.school" label="毕业院校" clearable placeholder="请输入毕业院校" @input="setInputValue('school', $event)" />
					<van-field v-model="dataValue.major" label="专业" clearable placeholder="请输入专业" @input="setInputValue('major', $event)" />
					<van-field v-model="dataValue.workUnit" label="工作单位" clearable placeholder="请输入工作单位"
						@input="setInputValue('workUnit', $event)" />
					<van-field v-model="dataValue.address" label="通讯地址" clearable placeholder="请输入通讯地址" @input="setInputValue('address', $event)" />
					<van-field v-model="dataValue.email" label="电子邮箱" clearable placeholder="请输入电子邮箱" @input="setInputValue('email', $event)" />
					<van-field v-model="dataValue.languageSpecialty" label="外语特长" clearable placeholder="请输入外语特长"
						@input="setInputValue('languageSpecialty', $event)" /> -->
					<van-field
						clearable
						readonly
						required
						label="医生执照"
						class="upLoad"
					>
						<template slot="button" class="upLoadOn">
							<van-uploader class="cccc" name="addAnnexFileIds" :file-list="upLoad.addAnnexFileIds" :after-read="afterRead" @delete="deleteFile">
								<van-button>
									<van-icon name="plus" style="color:#47A49B;" />
								</van-button>
							</van-uploader>
						</template>
					</van-field>
				</van-cell-group>
			</view>
			<view class="signatureBox">
				<view class="signature row" :class="showPicker || isDialogShow?'canHidden':''">
					<van-cell title="本人签名" title-width="120rpx" value="仔细阅读医生承诺书后签名" required readonly :border="false" />
					<!-- <view v-if="!dataValue.signImg" class="images choose"></view> -->
					<sign v-if="!dataValue.signImg" @success="success" @close="signClose"></sign>
					<view v-else class="signImgs">
						<image class="images" :src="dataValue.signImg" mode=""></image>
						<van-icon class="closeSignimg" @click="delSignImg" name="close" />
					</view>
				</view>
			</view>
			
			<view class="signCheckbox">
				<van-checkbox :value="checked" checked-color="#02BF88" @change="onChange">
					<text>请仔细阅读</text>
					<text @click.stop="protocols" style="color: #02BF88;">医生承诺书</text>
				</van-checkbox>
			</view>
			
			<van-dialog use-slot title="可提供服务的时间" :show="dialogShow" show-cancel-button @close="onClose"
				@confirm="dialogConfirm" @getuserinfo="getUserInfo">
				<van-checkbox-group class="checkbox-group" :value="result" @change="onCheckbox">
					<van-checkbox class="checkbox" v-for="item in columnList" :key="item.id" shape="square"
						:name="item.id">{{ item.purposeName || item.periodName }}</van-checkbox>
				</van-checkbox-group>
			</van-dialog>
			<van-popup :show="showPicker" position="bottom">
				<van-picker v-if="pickerType === 'picker'" show-toolbar :value-key="valueType" :columns="columnList"
					@confirm="onConfirm" @cancel="showPicker = false" />
				<van-datetime-picker v-if="pickerType === 'timePicker'" type="date" title="选择年月日"
					:value="new Date().getTime()" @confirm="onConfirm" @cancel="showPicker = false" />
				<van-area v-if="pickerType === 'area'" :area-list=" areaList "
					columns-num="2"
					:columns-placeholder=" ['请选择', '请选择'] " title="省市" @confirm="onConfirm"
					@cancel="showPicker = false" />
			</van-popup>
			<view class="btnBox">
				<van-button class="btn" round type="primary" @click="submit">提交</van-button>
			</view>
		</view>
		<van-toast id='van-toast' />
		<van-dialog
		  use-slot
		  title="医生承诺书"
		  :show="isDialogShow"
			confirm-button-color="#02BF88"
		  @confirm="isDialogShow = false"
		>
		<protocol></protocol>
		</van-dialog>
	</view>
</template>

<script>
	import {
		areaList
	} from '@/utils/city';
	import {
		FormatTime
	} from "@/utils/index";
	import {
		formValidation
	} from '@/utils/regexp'
	import protocol from './protocol.vue'
	import {
		uploadFile
	} from '@/utils/uploadFile'
	import {
		getByOwn,
		userProfileAdd,
		userProfileEdit
	} from '@/api/my'
	import {
		fileById
	} from '@/api/common'
	import { deleteFile } from '@/api/common'
	import sign from '@/components/sign'
	let upLoad = {
		cureList: [],
		addAnnexFileIds: []
	}
	export default {
		name: 'authentication',
		components: {
			protocol,
			sign
		},
		data() {
			return {
				width: '',
				height: '',
				chooseType: '', // 当前选择的值
				pickerType: 'picker', // 当前选择的类型
				valueType: '',
				columnList: [], //当前选中的列表数据
				areaList: areaList, //省市区数据
				showPicker: false,
				dialogShow: false,
				checked: false, //是否选中医生保证书
				isDialogShow: false, //查看医生保证书
				isShowSign: false, //签名
				result: [],
				upLoad: upLoad,
				dataValue: {
					name: '',
					phone: '',
					birthDate: '',
					cardNo: '',
					nativePlace: '湖南株洲',
					wechat: '',
					address: '',
					specialty: '',
					addPeriodIds: '',
					addPurposeIds: '',
					type: '3',
					sex: '',
					gender: '',
					education: '',
					areaName: '',
					resume: '',
					domicile: '',
					nation: '',
					political: '',
					school: '',
					major: '',
					workUnit: '',
					job: '',
					email: '',
					languageSpecialty: '',
					autograph: ''
				},
				rules: {
					name: [{
						required: true,
						message: '请填写姓名'
					}],
					phone: [{
							required: true,
							message: '请填写手机号'
						},
						{
							validate: /^1\d{10}$/,
							message: '手机号不正确'
						}
					],
					sex: [{
						required: true,
						message: '请选择性别'
					}],
					cardNo: [{
						required: true,
						message: '请输入身份证号码'
					},
					{
						validate: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
						message: '身份证号码不正确'
					}],
					nativePlace: [{
						required: true,
						message: '请输入籍贯'
					}],
					// education: [{
					// 	required: true,
					// 	message: '请选择文化程度'
					// }],
					// wechat: [{
					// 	required: true,
					// 	message: '请输入微信号码'
					// }],
					// specialty: [{
					// 	required: true,
					// 	message: '请输入特长'
					// }],
					// addPeriodIds:[
					// 	{
					// 		required: true,
					// 		message: '请选择提供服务时间'
					// 	}
					// ],
					// addPurposeIds:[
					// 	{
					// 		required: true,
					// 		message: '请选择服务方向'
					// 	}
					// ]
				},
				sexList: [{
						id: '1',
						name: '男'
					},
					{
						id: '2',
						name: '女'
					},
					{
						id: '0',
						name: '保密'
					}
				],
				isAdd: false,
				checkVal: []
			}
		},
		computed: {
			orientationList() {
				return this.$storage.getItem('purposeGetAll')
			},
			weekList() {
				return this.$storage.getItem('periodGetAll')
			},
			educationList() {
				return this.$storage.getItem('dict').educationList
			},
			birthday() {
				let a = this.dataValue.cardNo
				if (a && a.length == 18) {
					let b = a.slice(6,-4);
					b = b.substr(0,4) + '-' + b.substr(4,2) + '-' + b.substr(6)
					this.dataValue.birthDate = b;
					return b
				} else {
					this.dataValue.birthDate = ''
					return ''
				}
			}
		},
		mounted() {
			this.initWidth()
			this.getUsrInfo()
		},
		methods: {
			delSignImg() {
				deleteFile({ fileId: this.dataValue.autograph }).then(res => {
					this.dataValue.signImg = '';
					this.dataValue.autograph = '';
				})
			},
			close(e,data) {
				if (e == 'success') {
					if (data) {
						this.dataValue.autograph = data;
						this.isDialogShow = false;
					} else {
						this.$toast.fail('请签名');
					}
				} else {
					this.isDialogShow = false;
				}
			},
			getUsrInfo() {
				getByOwn().then(res => {
					if (res.data) {
						let dataInfo = res.data;
						Object.keys(dataInfo).forEach((key) => {
						 if (dataInfo[key] == 'null' || dataInfo[key] == 'undefined') {
							 dataInfo[key] = ''
						 }
						})
						this.dataValue = {
							...dataInfo,
							type: '3'
						}
						this.isAdd = true
						if (this.dataValue.gender) {
							this.sexList.filter(item => {
								if (item.id == this.dataValue.gender) {
									this.$set(this.dataValue, 'sex', item.name)
								}
							})
						}
						if (this.dataValue.phone) {
							this.dataValue.wechat = this.dataValue.phone
						}
						if (this.dataValue.headPortrait) {
							fileById({fileId: this.dataValue.headPortrait}).then(req => {
								if (req.data) {
									this.upLoad.cureList = [{url: req.data.accessUrl, id: this.dataValue.headPortrait}]
								}
							})
						}
						if (this.dataValue.annexFileIdList.length) {
							this.upLoad.addAnnexFileIds = []
							this.dataValue.annexFileIdList.map(item => {
								fileById({fileId: item}).then(req => {
									if (req.data.accessUrl) {
										this.upLoad.addAnnexFileIds.push({url: req.data.accessUrl, id: item})
									}
								})
							})
						}
						if (this.dataValue.autograph) {
							fileById({fileId: this.dataValue.autograph}).then(req => {
								if (req.data) {
									this.isShowSign = false;
									this.$set(this.dataValue, 'signImg', req.data.accessUrl);
								}
							})
						}
					}
				})
			},
			initWidth(formName) {
				let that = this;
				uni.getSystemInfo({
					success: function(res) {
						that.width = res.windowWidth;
					}
				});
			},
			onCheckbox(e) {
				var r = e.detail.filter(function(s) {
					return s && s.trim();
				});
				this.result = r;
			},
			onClose() {
				this.dialogShow = false
			},
			getUserInfo(event) {
			},
			setInputValue(e, s) {
				this.dataValue[e] = s.detail;
			},
			showPop(val, valueType, type = 'picker') {
				this.showPicker = true;
				this.columnList = this[val];
				this.chooseType = val;
				this.pickerType = type
				this.valueType = valueType
			},
			// 选择弹框后的数据
			onConfirm(e) {
				const val = e.detail.value
				const vals = e.detail.values
				switch (this.chooseType) {
					case 'sexList':
						this.dataValue.sex = val.name
						this.dataValue.gender = val.id
						break;
					case 'birthday':
						this.dataValue.birthDate = FormatTime(new Date(e.detail), "YYYY-MM-DD")
						break;
					case 'educationList':
						this.dataValue.education = val.name
						break;
					case 'areaList':
						let name = "";
						let id = "";
						vals.forEach(item => {
							if (name) {
								name += '-' + item.name
								id += ',' + item.code
							} else {
								name = item.name
								id = item.code
							}
						})
						this.dataValue.nativePlace = name
						break;

					case 'recoveryTime':
						this.dataValue.recoveryTime = FormatTime(new Date(e.detail), "YYYY-MM-DD")
						break;
					case 'diagnosisList':
						this.dataValue.diagnosisName = val.name
						this.dataValue.diagnosisType = val.id
						break;
					default:
						break;
				}
				this.showPicker = false;
			},
			dialogConfirm(e) {
				let val = []
				this[this.valueType].map(item => {
					this.result.map(el => {
						if (item.id === el){
							val.push(item.purposeName || item.periodName)
						}
					})
				})
				this.dataValue[this.chooseType + 'Name'] = val.toString()
				this.dataValue[this.chooseType] = this.result.toString()
			},
			setCheckValue(val, valueType) {
				if (this.valueType != valueType) {
					this.result = []
				}
				this.dialogShow = true;
				this.columnList = this[valueType];
				this.chooseType = val;
				this.valueType = valueType;
			},
			onChange(event) {
				this.checked = event.detail
			},
			protocols() {
				this.isDialogShow = true
			},
			afterRead: (file, val) => {
				let that = this;
				let type = val.name;
				uploadFile({
					fileURL: '/file/uploadImage',
					filePath: file.path
				}).then(res => {
					upLoad[type].push({
						url: res.file.accessUrl,
						id: res.file.fileId
					})
				})
			},
			deleteFile(e) {
				let obj = this.upLoad[e.detail.name][e.detail.index]
				this.upLoad[e.detail.name].splice([e.detail.index],1)
				this.$nextTick(() =>{
					deleteFile({ fileId: obj.id })
				})
			},
			//签名成功/
			success(file) {
				this.isShowSign = false;
				this.dataValue.signImg = file.accessUrl;
				this.dataValue.autograph = file.fileId;
			},
			// 关闭
			signClose() {
				this.isShowSign = false;
			},
			submit() {
				if (!this.upLoad.cureList.length) {
					return this.$toast.fail('请上传头像');
				}
				formValidation({
					data: this.dataValue,
					rules: this.rules
				}).then(res => {
					if (!this.upLoad.addAnnexFileIds.length) {
						return this.$toast.fail('请上传医生执照');
					}
					if (!this.dataValue.autograph) {
						return this.$toast.fail('请填写本人签名');
					}
					if (!this.checked) {
						return this.$toast.fail('请勾选医生承诺书');
					}
					this.$showModal({
						title: '提示',
						content: '是否提交您的认证信息？',
						showCancel: true,
					}, (suc) => {
						this.dataValue.headPortrait = this.upLoad.cureList[0].id;
						this.dataValue.addAnnexFileIds = this.upLoad.addAnnexFileIds[0].id;
						if (!this.isAdd) {
							userProfileAdd(this.dataValue).then(res => {
								if (res.status == 1) {
									uni.showToast({
										title: '新增成功',
										duration: 2000,
										icon:'success'
									})
									setTimeout(() => {
										uni.switchTab({
											url: '/pages/tabbar/index/index'
										});
									},1500)
								} else {
									this.$toast.fail(res.message)
								}
							})
						} else {
							userProfileEdit(this.dataValue).then(res => {
								if (res.status == 1) {
									this.$toast.success('提交成功, 等待审核')
									setTimeout(() => {
										uni.switchTab({
											url: '/pages/tabbar/index/index'
										});
									},1500)
								} else {
									this.$toast.fail(res.message)
								}
							})
						}
					})
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.authentication {
		width: 100%;
		box-sizing: border-box;
		position: relative;
		padding: 20rpx 0 0;

		.title {
			font-size: 36rpx;

			&.weight {
				font-weight: bold;
			}
		}

		.module {
			padding: 0 20rpx;

			.upLoad {
				display: flex;
				flex-direction: column;
				text-align: center;
				margin-bottom: 30rpx;
				/deep/ .van-uploader__wrapper {
					width: auto !important;
				}
				text {
					margin-top: 10rpx;
					font-size: 24rpx;
				}

				/deep/ .van-button {
					width: 180rpx;
					height: 120rpx;
					padding: 0;
				}
			}
		}
		
		.signatureBox {
			margin-top: 40rpx;
			margin-left: 6%;
			.signature {
				display: flex;
				flex-direction: column;
				padding-bottom: 10%;
				font-size: 28rpx;
				/deep/ .van-cell__value {
					text-align: left;
				}
				.signImgs {
					position: relative;
					.images {
						width: 200rpx;
						height: 200rpx;
						border: 1px solid #ccc;
					}
					.closeSignimg {
						position: absolute;
						left: 188rpx;
						top: -10rpx;
						font-size: 16px;
					}
				}
				.choose {
					position: relative;
					&::before {
						content: "";
						position: absolute;
						left: 50%;
						top: 20%;
						width: 10rpx;
						height: 60%;
						margin-left: -4rpx;
						background-color:#ccc;
					}
					&::after {
						content: "";
						position: absolute;
						left: 20%;
						top: 50%;
						width: 60%;
						height: 10rpx;
						margin-top: -4rpx;
						background-color:#ccc;
					}
				}
				.handwriting {
					flex: 2;
				}
			}
		}
		.signCheckbox {
			padding: 0 40rpx;
			font-size: 28rpx;
			/deep/ .van-checkbox__icon {
				font-size: 30rpx !important;
			}
		}
		.btnBox {
			font-size: 24rpx;
			margin-top: 10rpx;
			padding: 10rpx 32rpx;
			box-sizing: border-box;
			width: 100%;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			background-color: #FFFFFF;
			z-index: 2;

			.btn {
				user-select: none;
				margin-top: 10rpx;
				width: 100%;
				height: 80rpx;

				/deep/ .van-button {
					width: 100%;
					height: 100%;
					background-color: #02BF88;
					color: #FFFFFF;
				}
			}
		}
	}

	.checkbox-group {
		display: flex;
		flex-direction: row;
		flex-wrap: wrap;
		width: 100%;
		padding: 0 20rpx;
		box-sizing: border-box;
	}

	.checkbox {
		width: 33%;
		font-size: 26rpx;
		margin-top: 10rpx;
	}

	.cellGroup {
		display: flex;
		flex-wrap: wrap;

		.van-cell-group {
			display: flex;
			flex-wrap: wrap;
		}
	}
	.upLoad /deep/ .van-field__input {
		display: none;
		/deep/ .van-cell {
			padding-left: 0 !important;
		}
	}
	.upLoadOn {
		text-align: left;
		margin-top: 30rpx;
		.upLoadTitle {
			color: #000;
		}
		/deep/ .van-button--normal {
			padding: 90rpx 80rpx !important;
		}
	}
	.cell {
		/deep/ .van-cell {
			flex-direction: row;
			padding: 0;
			width: 100%;

			.van-cell__title {
				flex: inherit;
			}

			.van-cell__value {
				flex: inherit;
			}
		}
	}
</style>
